# coding=utf-8

# from selenium import webdriver  # 从selenium导入webdriver
# from selenium.webdriver.common.by import By

from lxml import etree

from flask import Flask, request
# from flask import request
# from flask_cors import CORS
import json
import sys
import random
import time
import pymysql
from urllib import parse
import qidian
import zhangyue
import zongheng
# import biquge
import readnovel

from abc import abstractclassmethod, ABCMeta

appfile = Flask(__name__)

# # r'/*' 是通配符，让本服务器所有的URL 都允许跨域请求
# CORS(appfile, resources=r'/*')

# 数据库
server_host = 'rm-2ze37q7aa2pf9a89uo.mysql.rds.aliyuncs.com'
user = 'zhoufeng'
passwd = 'cdddbs2Bjsnb'
db = 'novel'
port = 3306


# 根据参数返回相应的小说章节
# params:
#     link    链接
#     bookName    书名
#     bookId  书籍id
#     chapterName 章节名
#     platform    平台
@appfile.route('/getNovel', methods=['GET'])
def getNovel():
    link = request.values.get('link')
    bookName = request.values.get('bookName')
    bookId = request.values.get('bookId')
    chapterName = request.values.get('chapterName')
    platform = request.values.get('platform')

    if link:
        link = parse.unquote(link)

    result = isExistData(bookId, bookName, chapterName, platform, link)

    if result['code'] == 1:
        if platform == 'zongheng':
            result = zongheng.getNovel(link, bookName, bookId, chapterName)
        elif platform == 'qidian':
            result = qidian.get_chapter(link, chapterName, platform)
        # elif platform == 'biquge':
        #     result = biquge.getNovel(link, bookName, bookId, chapterName, platform)
        elif platform == 'zhangyue':
            result = zhangyue.get_chapter(link, chapterName, platform)
        elif platform == 'readnovel':
            result = readnovel.getNovel(link, bookName, bookId, chapterName, platform)

        
    # result = zongheng.getWholeNovel(link, bookName, bookId, platform)
    
    # return result
    return json.dumps(result, ensure_ascii=False)


# 检测符合条件的数据是否存在,存在则返回
def isExistData(bookId, bookName, chapterName, platform, link):
    conn = pymysql.Connect(host=server_host, port=port,
                           user=user, passwd=passwd, db=db, charset='utf8')

    result = {
        "code": 0,
        "info": "",
        "msg": []
    }
    
    with conn.cursor() as cursor:
        sql = "SELECT content FROM novel WHERE book_id='{0}' AND book_name='{1}' AND chapter_name='{2}' AND platform='{3}' AND link='{4}'".format(bookId, bookName.strip(), chapterName.strip(), platform, link)
        cursor.execute(sql)

        if cursor.rowcount == 1:
            # 获取所有记录列表
            results = cursor.fetchone()
            for row in results:
                result['msg'] = row.split('^^^')
        else:
            result['code'] = 1
            result['info'] = '暂无数据'
        
        cursor.close()
    conn.close()

    return result

# 插入数据
def insertData(bookId, bookName, chapterId, chapterName, contentArr, lastUpdateTime, auth_id, platform, link):
    conn = pymysql.Connect(host=server_host, port=port,
                           user=user, passwd=passwd, db=db, charset='utf8')

    result = {
        "code": 0,
        "info": ''
    }

    with conn.cursor() as cursor:

        sql = '''INSERT IGNORE INTO `novel`.`novel` (
            `book_id`, 
            `book_name`, 
            `chapter_id`, 
            `chapter_name`, 
            `content`, 
            `auth_update_time`, 
            `auth_id`, 
            `platform`, 
            `link`) VALUES ({0}, '{1}', '{2}', '{3}', '{4}', '{5}', '{6}', '{7}', '{8}')'''.format(bookId, bookName.strip(), chapterId, chapterName.strip(), '^^^'.join(contentArr).strip(), lastUpdateTime, auth_id, platform, link)

        # sql = "INSERT INTO `novel`.`novel` (`book_id`, `book_name`, `chapter_name`, `content`,, `platform`, `auth_update_time`, `link`) VALUES ('{0}', '{1}', '{2}', '{3}', '{4}', '{5}', '{6}')".format(bookId, bookName, chapterName, '^^^'.join(contentArr), platform, time.time(), link)

        cursor.execute(sql)
        conn.commit()
        
        cursor.close()
    conn.close()

    return result


# 插入作者相关数据
def insert_auth_data(auth_id, auth_name, platform):
    conn = pymysql.Connect(host=server_host, port=port,
                           user=user, passwd=passwd, db=db, charset='utf8')

    result = {
        "code": 0,
        "info": ''
    }

    with conn.cursor() as cursor:
        sql = "INSERT IGNORE INTO `novel`.`auth_info` (`auth_id`, `auth_name`, `platform`) VALUES ('{0}', '{1}', '{2}')".format(auth_id, auth_name, platform)

        cursor.execute(sql)
        conn.commit()

        cursor.close()
    conn.close()

    return result

# 根据参数返回转换后的数字
@appfile.route('/convertNum', methods=['POST'])
def convertNum():
    link = request.values.get('link')
    content = request.values.get('content')
    platform = request.values.get('platform')

    print(link, content, platform)
    if platform == 'qidian':
        result = qidian.convert_num(link, content)
    else:
        result = ''
    return result

if __name__ == '__main__':
    appfile.debug = True
    appfile.run(host='0.0.0.0', port=8085)